package com.dq.controller.in.base;

import com.dq.exception.customException.AdminException;
import com.dq.domain.base.AbstractEntity;

import com.dq.domain.sys.section.SysSection;
import com.dq.xss.SQLFilter;
import io.swagger.annotations.ApiModelProperty;
import lombok.Data;
import org.apache.commons.lang3.StringUtils;

import java.lang.reflect.Field;
import java.util.HashMap;
import java.util.Map;

/**
 * @author  gewenzhen
 */
@Data
public class BaseAdminQuery  extends AbstractEntity{
    @ApiModelProperty(value = "排序字段，可不传，不传时，排序方式也不用传")
    public String sidx;
    @ApiModelProperty(value = "排序方式", example = "desc/asc")
    public String order;

    @ApiModelProperty(value = "页数")
    public Integer page;
    @ApiModelProperty(value = "每页数")
    public Integer size;


    @ApiModelProperty(value = "所属组织部门",hidden = true)
    public SysSection section;

    /**
     * 负初始值
     */
    public void format() {
        if (page == null || page < 1) {
            page = 1;
        }
        if (size == null || size < 1) {
            size = 10;
        }
        sidx = StringUtils.isNotBlank(sidx) ? SQLFilter.sqlInject(sidx) : sidx;
        order = StringUtils.isNotBlank(order) ? SQLFilter.sqlInject(order) : order;
    }

    public static String likeSql(String value) {
        return "%" + value + "%";
    }

    public Map<String, Object> parseMap() throws AdminException {
        Map<String, Object> map = new HashMap<>(16);
        try {
            for (Field param : this.getClass().getFields()) {
                String paramName = param.getName();
                param.setAccessible(true);
                Object o = param.get(this);
                if (o instanceof String) {
                    if (StringUtils.isNotBlank(o + "")) {
                        map.put(paramName, param.get(this));
                    }
                } else if (o instanceof Enum) {
                    if (!((Enum) o).name().equals("all")) {
                        map.put(paramName, param.get(this));
                    }
                } else {
                    if (o != null) {
                        map.put(paramName, param.get(this));
                    }
                }
            }
            return map;
        } catch (IllegalAccessException e) {
            throw new AdminException("查询转换失败");
        }
    }
}
